package com.joven.shelltest.interceptor;

import cn.hutool.json.JSONUtil;
import com.joven.shelltest.annotation.AutoIdempotent;
import com.joven.shelltest.dto.ResultDto;
import com.joven.shelltest.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 防重复提交注解
 *
 * @Author wzj
 * @Date 2023-07-27 08:56
 **/
@Component
public class AutoIdempotentInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //被ApiIdempotment标记的扫描
        AutoIdempotent methodAnnotation = method.getAnnotation(AutoIdempotent.class);
        if (methodAnnotation != null) {
//            try {
                long expire = methodAnnotation.expire();
//                String methodName = request.getMethod();

            // 获取请求的HTTP方法名
            String httpMethod = request.getMethod();

            // 获取请求的URI路径
            String requestURI = request.getRequestURI();

            // 解析URI路径，获取方法名
            String methodName = null;
            if (requestURI != null && requestURI.length() > 0) {
                String[] uriParts = requestURI.split("/");
                if (uriParts.length > 0) {
                    methodName = uriParts[uriParts.length - 1];
                }
            }
            // 根据HTTP方法名添加前缀
            if (httpMethod != null && httpMethod.length() > 0 && methodName != null && methodName.length() > 0) {
                methodName = httpMethod.toLowerCase() + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
            }

//                return tokenService.checkToken(request);
//            } catch (Exception ex) {
//                ResultDto resultDto = new ResultDto();
//                resultDto.setMessage(ex.getMessage());
//                resultDto.setStatusCode(HttpStatus.BAD_REQUEST.value());
//                writeReturnJson(response, JSONUtil.toJsonStr(resultDto));
//                throw ex;
//            }
            if(!tokenService.checkToken(methodName,expire)){
                ResultDto resultDto = new ResultDto();
                resultDto.setMessage("请勿重复请求");
                resultDto.setStatusCode(HttpStatus.BAD_REQUEST.value());
                writeReturnJson(response, JSONUtil.toJsonStr(resultDto));
            }

        }
        //必须返回true,否则会被拦截一切请求
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 返回的json值
     *
     * @param response
     * @param json
     * @throws Exception
     */
    private void writeReturnJson(HttpServletResponse response, String json) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
